import * as React from 'react';
import { Form, Select, Field, Input, Balloon, Badge } from '@teamix/ui';
import { getCachedRepoValue } from 'utils/repoIdCache';
import { YunxiaoIcon, ButtonIcon } from '@alife/devops-ui';
import { navigate, getPathWithNoRootPath } from 'utils/router';
import MemberTrigger from 'components/memberTrigger';
import Popup from 'components/popup';
import track from 'utils/track';
import PathEllipsis from 'components/pathEllipsis';
import utils from 'utils';
import isequal from 'lodash.isequal';
import intl from '../../locale';
import './index.scss';
const { user, pathResource } = window.FORCE;
const { Tooltip } = Balloon;

const userData = [
  {
    name: user.nickname || user.realName,
    _userId: user.id,
  },
];

const formItemLayout = {
  labelCol: {
    span: 6,
  },

  wrapperCol: {
    fixedSpan: 12,
  },
};

const maxTagPlaceholder = (selectedValues, totalValues) => {
  const trigger = <span>{`${selectedValues.length}/${totalValues.length}`}</span>;
  const labels = selectedValues.map((obj) => obj.label);
  return <Tooltip trigger={trigger}>{labels.join(', ')}</Tooltip>;
};

export default class AdvancedSearch extends React.Component {
  constructor(props) {
    super(props);
    this.formProIds = '';
    this.field = new Field(this, {
      onChange: () => {
        this.dataTrack();
        this.setAdvancedSearchDataAndDoSearch();
      },
    });

    this.cacheKey = getCachedRepoValue('user');

    this.state = {
      pageType: null,
      authorData: userData,
      couldChangeAuthor: true,
      assigneeData: userData,
      couldChangeAssignee: true,
      badgeCount: 1,
      stateRepoData: [],
      // 记录初始化的initFormValue，为了比较是否有过滤条件
      searchProjectValue: null,
    };
  }

  componentDidMount() {
    if (pathResource && pathResource.type === 'PROJECT') {
      this.setState({
        pageType: 'project',
      });

      this.resetFormByNavKeyAndTabkey();
    } else if (pathResource && pathResource.type === 'GROUP') {
      this.setState({
        pageType: 'group',
      });

      this.onGroupSubProjectList();
      this.resetFormByNavKeyAndTabkey();
    } else {
      this.setState({
        pageType: 'dashboard',
      });

      this.onProjectList();
      this.initAdvancedSearchForm();
      // this.resetFormByNavKeyAndTabkey();
    }
  }

  dataTrack = () => {
    const { pageType } = this.state;
    if (pageType === 'project') {
      track({
        action: 'filter_mr',
        page: 'Repo-MRs',
      });
    } else if (pageType === 'group') {
      track({
        action: 'filter_mr',
        page: 'Group-MRs',
      });
    } else {
      track({
        action: 'filter_mr',
        page: 'Organization-MRs-All',
      });
    }
  };

  // navKey 或 tabKey 变化时，重置表单
  componentDidUpdate(prevProps) {
    const { addr } = this.props;
    const urlAddr = utils.getUrlSearchParam('addr') || 'icon';
    if (this.props.searchValue !== prevProps.searchValue) {
      if (this.props.searchValue === 'created') {
        this.resetFormByNavKeyAndTabkey();
      } else {
        this.setState({
          pageType: 'dashboard',
        });

        urlAddr === addr && this.onProjectList();
        this.initAdvancedSearchForm();
      }
    } else if (this.props.activeKey !== prevProps.activeKey) {
      this.setAdvancedSearchDataAndDoSearch(true, urlAddr !== addr);
    }
  }

  // 获取表单数据，设置 advancedSearch，并触发查询
  setAdvancedSearchDataAndDoSearch = (notCrSearchTags, onlySave) => {
    this.field.validate((errors) => {
      if (!errors) {
        const formData = this.field.getValues();
        const { stateRepoData } = this.state;
        const { crSearchTags, activeKey, repoDataSource } = this.props;
        if (crSearchTags && !notCrSearchTags) {
          const formProIds = formData.project_ids ? formData.project_ids : [];
          const repoData = formProIds
            .map((item) => {
              const formDataSource = repoDataSource[0].children.filter((v) => v.value === item);
              const fromState = stateRepoData.filter((v) => v.value === item);
              return formDataSource[0] || fromState[0];
            })
            .filter((v) => v && v.value);
          crSearchTags({
            repositoryData: repoData,
          });

          this.setState({
            stateRepoData: repoData,
          });

          const { authorData, assigneeData } = this.state;
          const formDataStr = JSON.stringify({
            authorData,
            assigneeData,
            repoData,
          });

          utils.setCachedData(`advanced-search-${this.cacheKey}`, formDataStr);
          const { pathname } = window.location;
          const { addr = 'icon' } = this.props;
          navigate(`${getPathWithNoRootPath(pathname)}?navKey=all&search=${new Date().getTime()}&addr=${addr}`);
          this.initAdvancedSearchForm();
          return;
        }
        if (formData.author_tb_ids) {
          formData.author_tb_ids = formData.author_tb_ids.join(',');
        }
        if (this.state.pageType === 'project') {
          formData.project_ids = pathResource.id;
        } else if (this.state.pageType === 'group') {
          formData.group_ids = pathResource.id;
          if (formData.project_ids) {
            formData.project_ids = formData.project_ids.join(',');
          }
        } else {
          if (formData.project_ids) {
            formData.project_ids = formData.project_ids.join(',');
          }

          if (formData.group_ids) {
            formData.group_ids = formData.group_ids.join(',');
          }
        }
        if (formData.assignee_tb_ids) {
          formData.assignee_tb_ids = formData.assignee_tb_ids.join(',');
        }
        if (activeKey) {
          formData.state = activeKey;
        }
        // if (formData.subscriber_tb_ids) {
        //   formData.subscriber_tb_ids = formData.subscriber_tb_ids.join(',');
        // }
        this.props.setAdvancedSearch(formData, onlySave);
        this.initAdvancedSearchForm();
      }
    });
  };

  initAdvancedSearchForm = () => {
    const { crSearchTags } = this.props;
    if (crSearchTags) {
      const formDataStr = utils.getCachedData(`advanced-search-${this.cacheKey}`);
      let formData = {
        authorData: formDataStr === 'created' ? userData : [],
        assigneeData: [],
        repoData: [],
      };

      try {
        if (formDataStr) {
          formData = JSON.parse(formDataStr);
        }
        // eslint-disable-next-line no-empty
      } catch (err) {}
      const { authorData, assigneeData, repoData } = formData;
      this.field.setValues({
        project_ids: repoData.map((v) => v.value),
        author_tb_ids: authorData.map((item) => item._userId || item.tb_user_id),
      });

      crSearchTags({
        authorData,
        assigneeData,
        repositoryData: repoData,
      });

      this.setState(
        {
          stateRepoData: repoData,
          authorData,
          assigneeData,
          badgeCount: authorData.length + assigneeData.length + repoData.length,
        },

        () => {
          // this.setAdvancedSearchDataAndDoSearch(true);
        },
      );
    }
  };

  // 根据 navKey 和 tabKey 重置表单
  resetFormByNavKeyAndTabkey = (flag) => {
    const { tabKey, authControl, searchValue } = this.props;
    let initFormValues;
    if (this.state.pageType === 'project') {
      initFormValues = {
        state: tabKey,
        project_ids: null,
        author_tb_ids: null,
        assignee_tb_ids: null,
        // subscriber_ids: null,
      };
      this.field.setValues(initFormValues);
      this.setState({
        authorData: [],
        assigneeData: [],
      });
    } else if (this.state.pageType === 'group') {
      initFormValues = {
        state: tabKey,
        project_ids: null,
        author_tb_ids: null,
        assignee_tb_ids: null,
        group_ids: null,
        // subscriber_ids: null,
      };
      this.field.setValues(initFormValues);
      this.setState({
        authorData: [],
        assigneeData: [],
      });
    } else {
      const ids = userData.map((item) => item._userId || item.tb_user_id);

      initFormValues = {
        state: tabKey,
        project_ids: null,
        author_tb_ids: searchValue === 'created' ? ids : null,
        assignee_tb_ids: null,
        // subscriber_ids: navKey === 'cc' ? ids : null,
      };
      this.field.setValues(initFormValues);
      let curAuthorData = [];
      let curAssigneeData = [];
      if (searchValue === 'created') {
        curAuthorData = userData;
        if (authControl) {
          this.setState({ couldChangeAuthor: true });
        } else {
          this.setState({ couldChangeAuthor: false });
        }
      } else {
        curAuthorData = [];
        this.setState({ couldChangeAuthor: true });
      }

      if (searchValue === 'reviewed') {
        curAssigneeData = userData;
        if (authControl) {
          this.setState({ couldChangeAssignee: true });
        } else {
          this.setState({ couldChangeAssignee: false });
        }
      } else {
        curAssigneeData = [];
        this.setState({ couldChangeAssignee: true });
      }

      const { crSearchTags = () => {} } = this.props;
      if (flag) {
        crSearchTags({
          authorData: [],
          assigneeData: [],
          subscriberData: [],
          repositoryData: [],
        });

        this.setState({
          authorData: [],
          assigneeData: [],
        });
      } else {
        crSearchTags({
          authorData: curAuthorData,
          assigneeData: curAssigneeData,
          repositoryData: [],
        });

        this.setState({
          authorData: curAuthorData,
          assigneeData: curAssigneeData,
          badgeCount: 1,
        });
      }
    }
  };

  resetFormByTags = () => {
    const formDataStr = utils.getCachedData(`advanced-search-${this.cacheKey}`);
    let formData = {
      authorData: formDataStr === 'created' ? userData : [],
      assigneeData: [],
      repoData: [],
    };

    try {
      if (formDataStr) {
        formData = JSON.parse(formDataStr);
      }
      // eslint-disable-next-line no-empty
    } catch (err) {}
    const { authorData = [], assigneeData = [], repoData = [] } = formData;
    this.field.setValues({
      project_ids: repoData.map((v) => v.value),
      author_tb_ids: authorData.map((item) => item._userId || item.tb_user_id),
    });

    this.setState({
      authorData,
      assigneeData,
      badgeCount: authorData.length + assigneeData.length + repoData.length,
    });
  };

  onAuthorChange = (value) => {
    this.setState(
      {
        authorData: value,
      },

      () => {
        const { crSearchTags = () => {} } = this.props;
        crSearchTags({
          authorData: value,
        });

        this.field.setValue(
          'author_tb_ids',
          value.map((item) => item._userId),
        );

        this.setAdvancedSearchDataAndDoSearch();
      },
    );
  };

  onSubscriberChange = (value) => {
    this.field.setValue(
      'subscriber_tb_ids',
      value.map((item) => item._userId),
    );

    this.setAdvancedSearchDataAndDoSearch();
  };

  onAssigneeChange = (value) => {
    this.setState(
      {
        assigneeData: value,
      },

      () => {
        const { crSearchTags = () => {} } = this.props;
        crSearchTags({
          assigneeData: value,
        });

        this.field.setValue(
          'assignee_tb_ids',
          value.map((item) => item._userId),
        );

        this.setAdvancedSearchDataAndDoSearch();
      },
    );
  };

  // 查询代码库，默认展示前5条
  onProjectList = (search, size = 5) => {
    const searchValue = search === undefined ? this.state.searchProjectValue : search;
    this.props.onProjectList(searchValue, size);
  };

  // 查询组所有子代码库
  onGroupSubProjectList = (search, size = 5) => {
    const searchValue = search === undefined ? this.state.searchProjectValue : search;
    this.props.onGroupSubProjectList(searchValue, size);
  };

  // 点击清除筛选表单内容返回到默认值
  onResetClick = () => {
    this.setState({
      searchProjectValue: null,
    });
    if (this.props.crSearchTags) {
      const { pathname } = window.location;
      const { addr } = this.props;
      navigate(`${getPathWithNoRootPath(pathname)}?navKey=all&addr=${addr}`);
      utils.setCachedData(`advanced-search-${this.cacheKey}`, '');
      this.initAdvancedSearchForm();
    } else {
      this.resetFormByNavKeyAndTabkey(true);
      this.setAdvancedSearchDataAndDoSearch();
    }
  };

  getBadgeDot = () => {
    const values = this.field.getValues();
    const { initFormValues } = this.state;
    if (!values) {
      return false;
    }
    return !isequal(values, initFormValues);
  };

  render() {
    const { renderHtml, crSearchTags, repoDataSource } = this.props;
    const { field } = this;
    const { init } = field;
    const { pageType, badgeCount, stateRepoData } = this.state;
    const fullName =
      pathResource && pathResource.fullName ? pathResource.fullName.replace(' / ', '/') : '';
    const fullNameArr = fullName.split('/') || [];
    const trigger = badgeCount ? (
      <Badge count={badgeCount}>
        <ButtonIcon name="filter-line" />
      </Badge>
    ) : (
      <Badge>
        <ButtonIcon name="filter-line" />
      </Badge>
    );

    const hasDot = this.getBadgeDot();
    const notCrTrigger = (
      <Badge dot={hasDot}>
        <ButtonIcon name="filter-line" type="primary" />
      </Badge>
    );

    let selectDataSource = stateRepoData;
    if (repoDataSource && repoDataSource[0] && repoDataSource[0].children) {
      selectDataSource = [...repoDataSource[0].children, ...stateRepoData];
    }
    const dataSourceSet = {};
    selectDataSource = selectDataSource
      .map((v) => {
        if (dataSourceSet[v.value]) {
          return undefined;
        }
        dataSourceSet[v.value] = true;
        return v;
      })
      .filter((o) => o !== undefined);
      if (repoDataSource.length && repoDataSource[0].children.length === 0) {
        repoDataSource[0].label = '暂无匹配数据';
      }
    return (
      <Popup
        className={repoDataSource.length && repoDataSource[0].children.length === 0 && 'cr-advanced-search-dashbord-repo-style'}
        trigger={crSearchTags === undefined ? notCrTrigger : renderHtml || trigger}
        triggerType="click"
        footer={
          <Form.Item style={{ marginBottom: '0px' }}>
            <Form.Reset
              text
              type="primary"
              style={{ border: 0 }}
              onClick={this.onResetClick}
              toDefault
              className="advanced-search-form-btn"
            >
              <YunxiaoIcon type="delete-line" />
              {intl.get({
                id: 'code-assets.components.crAdvancedSearchDashbord.ClearAllFilterConditions',
                defaultMessage: '清除所有筛选条件',
              })}
            </Form.Reset>
          </Form.Item>
        }
      >
        <Form {...formItemLayout} labelTextAlign="left" field={field}>
          {pageType === 'group' ? (
            <Form.Item
              label={intl.get({
                id: 'code-assets.src.utils.locale.CodeGroup',
                defaultMessage: '代码组',
              })}
            >
              <Input readOnly disabled value={fullNameArr[1] || ''} />
            </Form.Item>
          ) : null}
          <Form.Item
            label={intl.get({
              id: 'code-assets.src.utils.locale.CodeBase',
              defaultMessage: '代码库',
            })}
          >
            {pageType === 'project' ? (
              <Input readOnly disabled value={fullNameArr[1] || ''} />
            ) : (
              <Select
                {...init('project_ids')}
                mode="multiple"
                filterLocal={false}
                showSearch
                followTrigger
                placeholder={intl.get({
                  id: 'code-assets.src.utils.locale.EnterACodeLibraryName.1',
                  defaultMessage: '请输入代码库名以搜索',
                })}
                dataSource={
                  this.state.selectVisible
                    ? repoDataSource
                    : [
                        {
                          label: intl.get({
                            id: 'code-assets.components.crAdvancedSearchDashbord.LastUpdated',
                            defaultMessage: '最近更新',
                          }),

                          children: selectDataSource,
                        },
                      ]
                }
                onVisibleChange={(v) => {
                  this.setState({
                    selectVisible: v,
                  });
                }}
                searchValue={this.state.searchProjectValue}
                onSearch={(value) => {
                  this.dataTrack();
                  this.setState({
                    searchProjectValue: value,
                  });
                  if (pageType === 'group') {
                    // 组内用搜子库接口
                    this.onGroupSubProjectList(value);
                  } else {
                    this.onProjectList(value);
                  }
                }}
                maxTagPlaceholder={maxTagPlaceholder}
                popupStyle={{ maxWidth: '240px' }}
                popupProps={{
                  className: 'at-path-select-popup',
                }}
                itemRender={(item) => {
                  const path = item.name_with_namespace;
                  return <PathEllipsis path={path} />;
                }}
              />
            )}
          </Form.Item>
          <Form.Item
            label={intl.get({
              id: 'code-assets.src.utils.locale.Founder',
              defaultMessage: '创建人',
            })}
          >
            {this.state.couldChangeAuthor ? (
              <div
                ref={(o) => {
                  this.aucontainer = o;
                }}
              >
                <MemberTrigger
                  title={intl.get({
                    id: 'code-assets.components.crAdvancedSearchDashbord.SelectTheCreator',
                    defaultMessage: '选择创建人',
                  })}
                  onChange={(value) => {
                    this.dataTrack();
                    this.onAuthorChange(value);
                  }}
                  value={this.state.authorData}
                  container={() => this.aucontainer}
                  noMore
                  multiple
                />
              </div>
            ) : (
              <Input disabled value={this.state.authorData[0].name} />
            )}
          </Form.Item>
          <Form.Item
            label={intl.get({
              id: 'code-assets.src.utils.locale.Reviewer',
              defaultMessage: '评审人',
            })}
          >
            {this.state.couldChangeAssignee ? (
              <div
                ref={(d) => {
                  this.recontainer = d;
                }}
              >
                <MemberTrigger
                  title={intl.get({
                    id: 'code-assets.components.crAdvancedSearchDashbord.SelectReviewer',
                    defaultMessage: '选择评审人',
                  })}
                  onChange={(value) => {
                    this.dataTrack();
                    this.onAssigneeChange(value);
                  }}
                  value={this.state.assigneeData}
                  container={() => this.recontainer}
                  noMore
                  multiple
                />
              </div>
            ) : (
              <Input disabled value={this.state.assigneeData[0].name} />
            )}
          </Form.Item>

          {/* <Form.Item label="评审状态" {...formItemLayout} style={{ marginBottom: 0 }}>
              <Select
                {...init('state')}
                followTrigger
              >
                <Select.Option value="opened">已开启</Select.Option>
                <Select.Option value="merged">已合并</Select.Option>
                <Select.Option value="closed">已关闭</Select.Option>
                <Select.Option value="all">全部</Select.Option>
              </Select>
             </Form.Item> */}
        </Form>
      </Popup>
    );
  }
}
